package io.adminboot.service.impl;

import io.adminboot.domain.form.LoginForm;
import io.adminboot.entity.User;
import io.adminboot.entity.UserExample;
import io.adminboot.exception.MyException;
import io.adminboot.repository.extend.UserExtMapper;
import io.adminboot.service.UserService;
import io.adminboot.system.validator.Assert;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserExtMapper userMapper;

	@Override
	public User queryByMobile(String mobile) {
		UserExample example = new UserExample();
		UserExample.Criteria criteria = example.createCriteria();
		criteria.andMobileEqualTo(mobile);
		List<User> list = userMapper.selectByExample(example);
		return list != null && list.size() > 0 ? list.get(0) : null;
	}

	@Override
	public User login(LoginForm form) {
		User user = queryByMobile(form.getMobile());
		Assert.isNull(user, "手机号或密码错误");

		// 密码错误
		if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
			throw new MyException("手机号或密码错误");
		}

		return user;
	}

	@Override
	public User getById(Long id) {
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public void insert(User user) {
		userMapper.insert(user);
	}
}
